import { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Image, ScrollView, MovableArea, MovableView } from '@tarojs/components'
import { staticUrl } from '@/utils'
import classnames from 'classnames'
import dayjs from 'dayjs'
import { getCouponWriteOffList, writeOffCoupon } from '@/api/coupon'
import { base64_decode, utf8to16 } from '@/utils/base64'
import './index.scss'

const couponBgIcon = staticUrl('/img/service/coupon-write-off.png')
const writeOffIcon = staticUrl('/img/service/write-off.png')

interface State {
  list: any,
  activeIndex: any
}
export default class Index extends Component {
  constructor (props) {
    super(props)
    this.state = {
      list: [],
      activeIndex: 0,
    }
  }
  state: State
  private PER_PAGE: number = 6
  private MAX_PAGE: number = 1
  private currPage: number = 1
  private orderLoaded: boolean = false
  private isPageEnd: boolean = false

  componentDidShow() {
    console.log(dayjs().subtract(1, 'month').format('YYYY-MM-DD'))
    this.getCouponWriteOffList()
  }

  getCouponWriteOffList(mode: string = 'init') {
    let { activeIndex } = this.state
    if (this.orderLoaded) return
    this.orderLoaded = true
    if (mode === 'init') {
      this.currPage = 1
      this.isPageEnd = false
    } else {
      this.currPage++
      this.isPageEnd = this.currPage > this.MAX_PAGE
      this.orderLoaded = false
    }
    if (this.isPageEnd) return
    let params: any = {
      query: {
        page: this.currPage,
        perPage: this.PER_PAGE,
      }
    }
    if (Number(activeIndex) > 0) {
      params.query.filter = { and: [{ usedAt: { "gt": dayjs().subtract(Number(activeIndex), 'month').unix() } }] }
    }
    Taro.showLoading({ title: '加载中' })
    getCouponWriteOffList(params).then(res => {
      this.orderLoaded = false
      Taro.hideLoading()
      const data = res.data.data
      if (mode === 'init') {
        this.MAX_PAGE = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
        this.setState({
          list: data
        })
      } else {
        const { list } = this.state
        this.setState({
          list: [...list, ...data]
        })
      }
    }).catch(e => {
      this.orderLoaded = false
      Taro.hideLoading()
    })
  }

  // 滚动加载
  scrollLoad(e) {
    this.getCouponWriteOffList('add')
  }

  //切换标签
  changeTab(e) {
    this.setState({
      activeIndex: e
    }, () => {
      this.getCouponWriteOffList()
    })
  }

  //年审卡券扫码核销
  couponWriteOffScan() {
    let _this = this
    Taro.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        var data = res.result
        let qrcode: any = null
        if (data) {
          qrcode = utf8to16(base64_decode(data))
        }
        if (qrcode) {
          console.log(qrcode)
          qrcode = JSON.parse(qrcode)
          Taro.showModal({
            title: '确定核销？',
            content: `券码：${qrcode.id} 面值：${qrcode.baseAmount}元 \r\n发放门店：${qrcode.belongStoreName}`,
            success: function (res) {
              if (res.confirm) {
                Taro.showLoading()
                writeOffCoupon({ qrcode: data }).then(res => {
                  Taro.hideLoading()
                  Taro.showToast({
                    title: '核销成功',
                    icon: 'success'
                  })
                  setTimeout(() => {
                    _this.getCouponWriteOffList()
                  }, 1000)

                }).catch(err => {
                  console.log(err)
                  Taro.showModal({
                    title: '提示',
                    content: err.data.data.message,
                    showCancel: false
                  })
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  }


  render() {
    let { activeIndex, list } = this.state
    return (
      <View>
        <View className='tab'>
          <View className='tab-item'><Text className={classnames(activeIndex === 0 && 'active')} onClick={() => this.changeTab(0)}>全部</Text></View>
          <View className='tab-item'><Text className={classnames(activeIndex === 1 && 'active')} onClick={() => this.changeTab(1)}>近一个月</Text></View>
          <View className='tab-item'><Text className={classnames(activeIndex === 3 && 'active')} onClick={() => this.changeTab(3)}>近三个月</Text></View>
          <View className='tab-item'><Text className={classnames(activeIndex === 6 && 'active')} onClick={() => this.changeTab(6)}>近半年</Text></View>
        </View>
        <ScrollView scrollY lowerThreshold={150} onScrollToLower={(e) => this.scrollLoad(e)} className='order-wrap'>
          <View className='coupon-list'>
            {
              list.map((item, itemIndex) => {
                return (
                  <View key={itemIndex} className='coupon-item' style={`background-image: url(${couponBgIcon})`}>
                    <View className='label'>￥<Text>{item.baseAmount}</Text></View>
                    <View className='info'>
                      <View className='text name'>{item.name}</View>
                      <View className='text'>车主账号：{item.mobileHidden}</View>
                      <View className='text'>来源门店：{item.storeName}</View>
                      <View className='text date'>核销时间：{dayjs.unix(item.usedAt).format('YYYY.MM.DD')}</View>
                    </View>
                  </View>
                )
              })
            }
          </View>
          <View className="page-base">已经到底了~</View>
        </ScrollView>
				{
					process.env.TARO_ENV === 'weapp' ?  <MovableArea className='movable'>
          <MovableView className='movable-view' direction='all' x={300} y={450}>
            <Image className='write-off-icon' src={writeOffIcon} onClick={() => this.couponWriteOffScan()}></Image>
          </MovableView>
        </MovableArea> : null
				}


      </View>
    )
  }
}
